Page({
  data: {
    members: [],
    loading: true
  },

  onLoad: function (options) {
    this.loadMembers()
  },

  onShow: function () {
    // 页面显示时刷新数据
    this.loadMembers()
  },

  loadMembers: function () {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    // 从服务器获取家庭成员数据
    wx.request({
      url: 'http://localhost:3000/api/members',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            members: res.data.data.members || [],
            loading: false
          });
        } else {
          console.error('获取家庭成员失败:', res.data.message);
          this.setData({ loading: false });
          wx.showToast({
            title: res.data.message || '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  navigateToDetail: function (e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/members/detail/detail?id=${id}`
    })
  },

  addNewMember: function () {
    wx.navigateTo({
      url: '/pages/members/add/add'
    })
  }
}) 